# -*- coding: utf-8 -*-
import threading
import time
from pynput import mouse, keyboard  
import pydirectinput 
import win32gui
import win32con
import win32api
from ctypes import windll
import mss
import numpy as np
import threading
import time
import psutil
import random
from datetime import datetime
global m  
m = mouse.Controller()
global move_flag
move_flag=0
global quit_flag
quit_flag = 0
global mode
mode = 0
# 档位参数配置 (垂直系数, 水平系数)
global gear_params
gear_params = {
    0: (4, 0, "默认模式"),          # 垂直系数, 水平系数, 说明
    1: (6, 1, "突击步枪-全自动"),    
    2: (5, 1, "冲锋枪"),         
    3: (3, 0, "狙击枪单点"),        
    4: (7, 2, "轻机枪连发")      
}
global current_gear
current_gear = 0  # 当前档位


def callback(k, li):
    global current_gear
    # 处理数字键切换档位
    # 处理数字键切换档位 (1-5)
    if k in ["'1'", "'2'", "'3'", "'4'", "'5'"]:
        new_gear = int(k.strip("'")) - 1
        if 0 <= new_gear < len(gear_params):
            current_gear = new_gear
            v, h, desc = gear_params[current_gear]
            print(f"【档位{current_gear+1}】{desc}\n垂直系数:{v} 水平系数:{h}")

def on_mouse_move(x, y):  
    pass
#    print(f'鼠标移动到位置: ({x}, {y})')  

def on_mouse_click(x, y, button, pressed):  
    global move_flag
    global mode
    s=str(button)
    if pressed:          
        if mode:
            if s=="Button.left":
                li=m.position        
                m.position=(li[0],0)
                move_flag = 1

        if s=="Button.right":
            mode = 1
            print("压枪模式 开启")
    else:  
        if s=="Button.left":
            move_flag = 0
        elif s=="Button.right":
            mode = 0
            print("压枪模式 关闭")
#        print(f'{button} 释放于位置: ({x}, {y})') 
        
def on_mouse_scroll(x, y, dx, dy):
    global current_gear
    if dy > 0:  # 向上滚动
        new_gear = current_gear - 1
    else:  # 向下滚动
        new_gear = current_gear + 1
        
    # 检查档位边界
    if 0 <= new_gear < len(gear_params):
        current_gear = new_gear
        v, h, desc = gear_params[current_gear]
        print(f"【档位{current_gear+1}】{desc}\n垂直系数:{v} 水平系数:{h}")
    # dx 和 dy 表示滚动的水平方向和垂直方向的量  
    # 在大多数鼠标上，只有 dy 会变化，表示垂直滚动  
#    print(f'Scrolled at {x}, {y} ({dx}, {dy})')  
 
 
def on_key_press(key):
    callback(str(key),[]);
  
def release_callback(k):
    global move_flag
    global quit_flag
    if k=="'j'":
       quit_flag=1
       move_flag=0
        
def on_key_release(key):  
    release_callback(str(key))
#    try:  
#        print(f'{key.char} 被释放')  
#    except AttributeError:  
#        print(f'{key} 被释放')  
  
global mouse_listener
global keyboard_listener
# 创建鼠标监听器  
mouse_listener = mouse.Listener(on_move=on_mouse_move, on_click=on_mouse_click,on_scroll=on_mouse_scroll)  

# 创建键盘监听器，同时监听按下和释放事件  
keyboard_listener = keyboard.Listener(on_press=on_key_press, on_release=on_key_release)  

def key_start():
    global mouse_listener
    global keyboard_listener
    mouse_listener.start() 
    keyboard_listener.start() 
    mouse_listener.join()  
    keyboard_listener.join() 
    
global t
t=threading.Thread(target=key_start)
t.setDaemon(True)
t.start()    

def down():
    vertical, horizontal, _ = gear_params[current_gear]
    # print(down)
    pydirectinput.move(int(horizontal), int(vertical))
    
    
def move_while():
    global move_flag
    global quit_flag
    global mode
    print(f"move_while:{move_flag},{quit_flag},{mode}")
    while quit_flag==0:
        time.sleep(0.01)
        while move_flag and mode:            
            time.sleep(0.01)   
            th=threading.Thread(target=down)
            th.setDaemon(True)
            th.start()
def main():
    global mouse_listener
    global keyboard_listener
    print("按住右键开启压枪 长按左键执行")
    print("数字键1-5切换压枪档位 (当前支持5个档位)")
    print("按J退出程序")
    v, h ,desc= gear_params[current_gear]
    print(f"当前档位{current_gear+1}：垂直系数{v} 水平系数{h}")

#    key_start()2
    move_while()
    keyboard_listener.stop()
    mouse_listener.stop()
    print("quit")

# 性能监控配置
STATS_UPDATE_INTERVAL = 1.0  # 状态更新间隔（秒）

class ScreenOverlay:
    def __init__(self):
        # 初始化YOLO模型
        # 性能监控数据
        self.stats = {
            'open': 0,
            'state': 0,
        }
        self.frame_count = 0
        self.total_inference_time = 0
                # 屏幕尺寸获取
        with mss.mss() as sct:
            monitor = sct.monitors[0]
            self.width = monitor['width']
            self.height = monitor['height']
            self.monitor = monitor

    
        # 启动线程
        self.running = True

        self.status_thread = threading.Thread(target=self._status_monitor_loop)

        self.status_thread.start()

        self.main_thread = threading.Thread(target= main)

        self.main_thread.start()
        self.wc = win32gui.WNDCLASS()
        self.wc.hInstance = win32gui.GetModuleHandle(None)
        self.wc.lpszClassName = "TransparentOverlay"
        self.wc.style = win32con.CS_HREDRAW | win32con.CS_VREDRAW
        self.wc.lpfnWndProc = self._wnd_proc
        self.class_atom = win32gui.RegisterClass(self.wc)
        self.timernum = 0
        self.hwnd = win32gui.CreateWindowEx(
            win32con.WS_EX_LAYERED | 
            win32con.WS_EX_TRANSPARENT |
            win32con.WS_EX_TOPMOST |
            win32con.WS_EX_NOACTIVATE,
            self.class_atom,
            "Overlay",
            win32con.WS_POPUP,
            0, 0, self.width, self.height,
            0, 0, self.wc.hInstance, None
        )

        # 使用颜色键实现透明背景
        windll.user32.SetLayeredWindowAttributes(
            self.hwnd,
            0x000000,  # 黑色作为透明色
            0,
            win32con.LWA_COLORKEY
        )
        
        # # 注册组合键
        # self.hotkey_id = 0x4000
        # if not windll.user32.RegisterHotKey(
        #     self.hwnd,
        #     self.hotkey_id,
        #     win32con.MOD_CONTROL | win32con.MOD_SHIFT,
        #     VK_Q
        # ):
        #     win32gui.DestroyWindow(self.hwnd)
        #     raise RuntimeError("无法注册热键")

        win32gui.ShowWindow(self.hwnd, win32con.SW_SHOW)
        win32gui.UpdateWindow(self.hwnd)
        win32gui.InvalidateRect(self.hwnd, None, True)

    def _wnd_proc(self, hwnd, msg, wParam, lParam):
        # print("_wnd_proc: %s" % msg)
        if msg == win32con.WM_HOTKEY:
            if wParam == self.hotkey_id:
                windll.user32.UnregisterHotKey(hwnd, self.hotkey_id)
                win32gui.DestroyWindow(hwnd)
                win32gui.PostQuitMessage(0)
                return 0
        elif msg == win32con.WM_PAINT:
            hdc, ps = win32gui.BeginPaint(hwnd)
            
            self._draw_rect(hdc)
            win32gui.EndPaint(hwnd, ps)
            return 0
        elif msg == win32con.WM_DESTROY:
            win32gui.PostQuitMessage(0)
            return 0
        return win32gui.DefWindowProc(hwnd, msg, wParam, lParam)

    def _draw_rect(self, hdc):
        pen = None
        brush = None
        text_brush = None
        try:
            # 清空背景
            background_brush = win32gui.CreateSolidBrush(0x000000)
            win32gui.FillRect(hdc, (0, 0, self.width, self.height), background_brush)
            # 创建字体
            font = win32gui.LOGFONT()
            font.lfHeight = 24
            font.lfWeight = 700
            hfont = win32gui.CreateFontIndirect(font)
            old_font = win32gui.SelectObject(hdc, hfont)

            # 设置文本颜色（白色）和背景（透明）
            text_color = win32api.RGB(0, 255, 0)
            old_color = win32gui.SetTextColor(hdc, text_color)
            text_brush = win32gui.GetStockObject(win32con.NULL_BRUSH)
            old_brush = win32gui.SelectObject(hdc, text_brush)

            # 绘制性能状态文本
            status_text = (
                f"状态: {self.stats['open']} | "
                f"参数: {self.stats['state']}% | "
 
            )
            # 使用DrawText替代TextOut
            rect = (10, 10, self.width, 50)  # 文本绘制区域
            win32gui.DrawText(
                hdc, 
                status_text, 
                -1,  # 自动计算文本长度
                rect, 
                win32con.DT_LEFT | win32con.DT_TOP | win32con.DT_SINGLELINE
            )

            # 恢复原始对象
            win32gui.SelectObject(hdc, old_font)
            win32gui.SetTextColor(hdc, old_color)
            win32gui.SelectObject(hdc, old_brush)
            # win32gui.SelectObject(hdc, old_pen)
            # win32gui.SelectObject(hdc, old_brush)
        finally:
            if pen: win32gui.DeleteObject(pen)
            if brush:win32gui.DeleteObject(background_brush)



   
    def _status_monitor_loop(self):
        """性能监控线程"""
        while self.running:
            # 计算时间间隔
            v, h ,desc= gear_params[current_gear]
            # print(f"当前档位{current_gear+1}：垂直系数{v} 水平系数{h}")
            global mode
            if mode == 1:
                self.stats['open'] = "O"
            else:
                self.stats['open'] = "x"
            self.frame_count = 0
            self.stats['state'] = f"档位{current_gear+1}: {desc} | 垂直:{v} 水平:{h}"
            time.sleep(0.1)
            win32gui.InvalidateRect(self.hwnd, None, True)

    def run(self):
        try:
            win32gui.PumpMessages()
        finally:
            self.running = False
            try:
                windll.user32.UnregisterHotKey(self.hwnd, self.hotkey_id)
            except:
                pass

            self.status_thread.join(timeout=1)





    #定义虚拟键码
VK_Q = 0x51
VK_F = 0x46  # F键
VK_R = 0x52  # R键 


if __name__ == '__main__':
    overlay = ScreenOverlay()
    overlay.run()
    # main()
